from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Optional
from app.core.database import get_db
from app import models, schemas
from app.services.question_service import QuestionService

router = APIRouter()

@router.get("/grades", response_model=List[schemas.Grade])
def get_grades(db: Session = Depends(get_db)):
    """获取所有年级"""
    return db.query(models.Grade).order_by(models.Grade.level).all()

@router.get("/grades/{grade_id}/knowledge-points", response_model=List[schemas.KnowledgePoint])
def get_knowledge_points(grade_id: int, db: Session = Depends(get_db)):
    """获取指定年级的知识点"""
    return db.query(models.KnowledgePoint).filter(models.KnowledgePoint.grade_id == grade_id).all()

@router.post("/generate-test", response_model=schemas.TestPaper)
def generate_test(
    config: schemas.TestConfig,
    db: Session = Depends(get_db)
):
    """根据配置生成测试试卷"""
    question_service = QuestionService(db)
    return question_service.generate_test_paper(config)

@router.post("/submit-test/{test_paper_id}", response_model=schemas.TestResult)
def submit_test(
    test_paper_id: int,
    answers: schemas.TestAnswers,
    db: Session = Depends(get_db)
):
    """提交测试答案并获取结果"""
    question_service = QuestionService(db)
    return question_service.submit_test(test_paper_id, answers)

@router.get("/test-papers/{test_paper_id}", response_model=schemas.TestPaper)
def get_test_paper(test_paper_id: int, db: Session = Depends(get_db)):
    """获取测试试卷详情"""
    test_paper = db.query(models.TestPaper).filter(models.TestPaper.id == test_paper_id).first()
    if not test_paper:
        raise HTTPException(status_code=404, detail="Test paper not found")
    return test_paper

@router.get("/test-attempts/{attempt_id}", response_model=schemas.TestAttempt)
def get_test_attempt(attempt_id: int, db: Session = Depends(get_db)):
    """获取测试尝试记录"""
    attempt = db.query(models.TestAttempt).filter(models.TestAttempt.id == attempt_id).first()
    if not attempt:
        raise HTTPException(status_code=404, detail="Test attempt not found")
    return attempt

@router.get("/history")
def get_history(
    db: Session = Depends(get_db),
    user_id: Optional[int] = Query(None),
    grade: Optional[int] = Query(None),
    start: Optional[str] = Query(None),
    end: Optional[str] = Query(None),
    page: int = 1,
    pageSize: int = 10,
    sortBy: Optional[str] = Query(None),
    sortOrder: Optional[str] = Query(None)
):
    query = db.query(models.TestAttempt).join(models.User)
    if user_id:
        query = query.filter(models.TestAttempt.user_id == user_id)
    if grade:
        query = query.filter(models.User.grade == grade)
    if start:
        query = query.filter(models.TestAttempt.submit_time >= start)
    if end:
        query = query.filter(models.TestAttempt.submit_time <= end)

    if sortBy:
        col = getattr(models.TestAttempt, sortBy, None)
        if col is not None:
            if sortOrder == 'desc':
                query = query.order_by(desc(col))
            else:
                query = query.order_by(col)
        else:
            query = query.order_by(desc(models.TestAttempt.id))
    else:
        query = query.order_by(desc(models.TestAttempt.id))

    total = query.count()
    items = query.offset((page - 1) * pageSize).limit(pageSize).all()

    def to_item(a: models.TestAttempt):
        duration_sec = None
        if a.start_time and a.submit_time:
            duration_sec = int((a.submit_time - a.start_time).total_seconds())
        return {
            "id": a.id,
            "finishedAt": a.submit_time.isoformat() if a.submit_time else None,
            "score": a.score,
            "durationSec": duration_sec,
            "wrongCount": (a.total_questions - a.correct_count) if (a.total_questions is not None and a.correct_count is not None) else None,
            "suggestions": a.suggestions or []
        }

    return {"items": [to_item(a) for a in items], "total": total}